
package de.justphil.tcg.tcgserver.game.mechanics.game;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Random;

import org.slf4j.Logger;

import com.hazelcast.nio.DataSerializable;

import static de.justphil.tcg.tcgserver.commons.logging.TCGLogging.*;

public class GameRandom implements DataSerializable {
	
	private static final long	serialVersionUID	= -20570691356481249L;
	private static final Logger	log					= gameLogger(GameRandom.class);
	private Random				random;
	private long				seed;
	private int					counter;
	
	/**
	 * Constructor which creates a new pseudo random number generator with the provided seed.
	 * 
	 * @param seed the seed value
	 */
	public GameRandom(long seed) {
	
		random = new Random(seed);
		log.info("Using seed: {}", seed);
		this.seed = seed;
	}
	
	public GameRandom() {
	
	}
	
	/**
	 * {@link Random}
	 */
	public int nextInt(int max) {
	
		counter++;
		return this.random.nextInt(max);
	}
	
	/**
	 * {@link Random}
	 */
	public double nextDouble() {
	
		counter += 2;
		return this.random.nextDouble();
	}
	
	public int getCount() {
	
		return counter;
	}
	
	@Override
	public void writeData(DataOutput out) throws IOException {
	
		out.writeLong(seed);
		out.writeInt(counter);
	}
	
	@Override
	public void readData(DataInput in) throws IOException {
	
		seed = in.readLong();
		counter = in.readInt();
		random = new Random(seed);
		log.debug("Forwarding the random {} times.", new Object[] {
			counter });
		for (int i = 0; i < counter; i++) {
			random.nextInt(1000);
		}
	}
}
